package com.smart.common.security;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author arnold.zhao
 * @date 2018/10/18 9:54
 */
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    private String defaultFailureUrl;


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        JSONObject json = new JSONObject();

        if (exception.getMessage().contains("No AuthenticationProvider found")) {
            json.put("status", "-1");
            json.put("msg", "账户或密码输入错误,请重新输入");
        } else if (exception.getMessage().contains("Maximum sessions")) {
            json.put("status", "-2");
            json.put("msg", "该账号已登录，不能重复登录");
        }

        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();


        out.println(json.toString());
    }

    public String getDefaultFailureUrl() {
        return defaultFailureUrl;
    }

    //设置对应的登录失败的跳转路径
    public void setDefaultFailureUrl(String defaultFailureUrl) {
        this.defaultFailureUrl = defaultFailureUrl;
    }
}
